#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;
const int N = 1e3 + 10;
int f[4][N];
vector<int>a[N];
int n, k;
int main()
{
    cin >> n >> k;
    for (int i = 0; i < n; i++) {
        int x;
        cin >> x;
        a[x % k].push_back(x);
    }
    memset(f, -0x3f, sizeof(f));
    f[0][0] = 0;
    for (int i = 0; i < k; i++) {
        sort(a[i].begin(), a[i].end());
        reverse(a[i].begin(), a[i].end());
        for (int u = 0; u < 3 && a[i].size(); u++) {
            int x = a[i][u];
            for (int j = 3; j >= 1; j--) {
                for (int m = 0; m < k; m++) {
                    f[j][m] = max(f[j][m], f[j - 1][(m - x % k + k) % k] + x);
                }
            }
        }
    }
    cout << f[3][0] << endl;
    return 0;
}